package com.zpf.controller;

import com.zpf.pojo.User;
import com.zpf.service.LoginService;
import com.zpf.service.impl.LoginServiceImpl;
import com.zpf.utils.Constants;
import com.zpf.utils.StrUtils;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

@WebServlet("/user")
public class loginServlet extends BaseServlet {
        LoginService loginService = new LoginServiceImpl();

     public void check(HttpServletRequest request,HttpServletResponse response) throws IOException {
            String username = request.getParameter("username");
            //2.调用service，到数据库中查询这个用户名是否可用，存在不可用
            boolean check = loginService.check(username);
            //3.将是否可用信息返回页面展示
            if(check){
                response.getWriter().write(Constants.NOT_HAS_USER);
            }else {
                response.getWriter().write(Constants.HAS_USER);
            }
        }
    //注册
    public String register(HttpServletRequest request,HttpServletResponse response) throws Exception {
        Map<String, String[]> parameterMap = request.getParameterMap();
        User user = new User();
        BeanUtils.populate(user, parameterMap);

        int count = loginService.createUser(user);
        //4.调转到注册成功界面
        if (count > 0) {
            //注册成功
            return "redirect:/login.jsp";
        } else {
            //注册失败
            return "redirect:/register.jsp";
        }

    }
    //登录
    public String login(HttpServletRequest request, HttpServletResponse response){
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        if (!(StrUtils.empty(username)||StrUtils.empty(password))) {
            return "forward:/login.jsp";
        }
        User user = loginService.login(username, password);
        if (user == null) {
            request.setAttribute("username",username);
            request.setAttribute("password",password);
            request.setAttribute("msg","用户名或者密码错误");
            //跳转到登录页面
            return "forward:/login.jsp";
        }
        return "redirect:/index.jsp";
    }


}